<?php

/**
 * @author: zhangxingning
 * @contact: zhixiao476@gmail.com
 * @file: Encrypt.php
 * @time: 2021/3/8 11:06
 * @desc:
 */


namespace App\Libraries;


class Encrypt
{
    /**
     * 加密
     * @author
     * @param  string $input
     * @param  string $key
     * @param  string $method
     * @param  string $iv
     * @return string
     */
    public static function encrypt($input, $key, $method = 'DES-ECB', $iv = null)
    {
        $iv = $iv ? $iv : self::createIv();
        return base64_encode(openssl_encrypt($input, $method, $key, OPENSSL_RAW_DATA, $method == 'DES-ECB' ? '' : $iv));
    }

    /**
     * 解密
     * @author
     * @param  string $input
     * @param  string $key
     * @param  string $method
     * @param  string $iv
     * @return string
     */
    public static function decrypt($input, $key, $method = 'DES-ECB', $iv = null)
    {
        $iv = $iv ? $iv : self::createIv();
        return openssl_decrypt(base64_decode($input), $method, $key, OPENSSL_RAW_DATA, $method == 'DES-ECB' ? '' : $iv);
    }

    /**
     * 这个玩意相当于java里的
     * byte[] iv = { 0, 0, 0, 0, 0,0, 0, 0 }
     * 也相当于C#里的
     * IV = new byte[8];
     * @author TechLee
     * @return [type] [description]
     */
    public static function createIv()
    {
        return self::hexToStr("0000000000000000");
    }

    public static function hexToStr($hex)
    {
        $string = '';
        for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        }
        return $string;
    }
}
